import { EditOutlined } from "@ant-design/icons";
import type { RedisClient, FieldValue } from "@linksaas-minapp/redis-proxy-api"
import { Button, Card, Descriptions, Form, Input, List, Modal, Space, message } from "antd"
import { useState, useEffect } from "react"

export interface HashValueProps {
    client: RedisClient;
    curKey: string;
}

function HashValue(props: HashValueProps) {
    const [valueList, setValueList] = useState<FieldValue[]>([]);
    const [newField, setNewField] = useState("");
    const [newValue, setNewValue] = useState("");
    const [showAddModal, setShowAddModal] = useState(false);
    const [editField, setEditField] = useState("");
    const [editValue, setEditValue] = useState("");

    const loadData = async () => {
        const res = await props.client.hashCommand().hgetAll(props.curKey);
        const resultList = [] as FieldValue[];
        let tmpList = [] as string[];
        for (const v of res) {
            tmpList.push(v);
            if (tmpList.length == 2) {
                resultList.push({
                    field: tmpList[0],
                    value: tmpList[1],
                });
                tmpList = [];
            }
        }
        setValueList(resultList);
    };

    const removeData = async (field: string) => {
        await props.client.hashCommand().hdel(props.curKey, [field]);
        const tmpList = valueList.filter(item => item.field != field);
        setValueList(tmpList);
    };

    const updateData = async () => {
        await props.client.hashCommand().hset(props.curKey, [{
            field: editField,
            value: editValue,
        }]);
        const tmpList = valueList.slice();
        const index = tmpList.findIndex(item => item.field == editField);
        if (index !== -1) {
            tmpList[index].value = editValue;
            setValueList(tmpList);
        }
        setEditField("");
        setEditValue("");
    };

    const addData = async () => {
        if (newField == "") {
            return;
        }
        const exist = await props.client.hashCommand().hexists(props.curKey, newField);
        if (exist == 1) {
            message.warning("键已经存在");
            return;
        }
        await props.client.hashCommand().hset(props.curKey, [{
            field: newField,
            value: newValue,
        }]);
        const tmpList = valueList.slice();
        tmpList.unshift({
            field: newField,
            value: newValue,
        });
        setValueList(tmpList);
        message.info("添加成功");
        setShowAddModal(false);
    }

    useEffect(() => {
        loadData();
    }, []);

    return (
        <Card extra={
            <Button type="primary" onClick={e => {
                e.stopPropagation();
                e.preventDefault();
                setNewField("");
                setNewValue("");
                setShowAddModal(true);
            }}>添加值</Button>
        }>
            <List dataSource={valueList}
                style={{ height: "calc(100vh - 280px)", overflowY: "auto" }}
                renderItem={item => (
                    <List.Item extra={
                        <Button danger type="link" onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            removeData(item.field);
                        }}>删除</Button>
                    }>
                        <Descriptions column={2}>
                            <Descriptions.Item label="键" style={{ paddingBottom: "0px" }}>{item.field}</Descriptions.Item>
                            <Descriptions.Item label="值" style={{ paddingBottom: "0px" }}>
                                <Space>
                                    {item.value}
                                    <a onClick={e => {
                                        e.stopPropagation();
                                        e.preventDefault();
                                        setEditField(item.field);
                                        setEditValue(item.value);
                                    }}><EditOutlined /></a>
                                </Space>
                            </Descriptions.Item>
                        </Descriptions>
                    </List.Item>
                )}
            />
            {editField != "" && (
                <Modal open title="修改值" okText="修改"
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setEditField("");
                    }}
                    onOk={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        updateData();
                    }}>
                    <Form>
                        <Form.Item label="值">
                            <Input value={editValue} onChange={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setEditValue(e.target.value);
                            }} />
                        </Form.Item>
                    </Form>
                </Modal>
            )}
            {showAddModal == true && (
                <Modal open title="添加值" okText="添加" okButtonProps={{ disabled: newField == "" }}
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setShowAddModal(false);
                    }}
                    onOk={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        addData();
                    }}>
                    <Form>
                        <Form.Item label="键:">
                            <Input value={newField} onChange={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setNewField(e.target.value);
                            }} />
                        </Form.Item>
                        <Form.Item label="值:">
                            <Input value={newValue} onChange={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setNewValue(e.target.value);
                            }} />
                        </Form.Item>
                    </Form>
                </Modal>
            )}
        </Card>
    );
}

export default HashValue;